package xyz.liut.onmyojihelper.view

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.PixelFormat
import android.view.Gravity
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.WindowManager
import android.view.WindowManager.LayoutParams.*
import android.widget.Button
import android.widget.LinearLayout
import xyz.liut.onmyojihelper.R
import xyz.liut.onmyojihelper.util.LogUtil
import xyz.liut.onmyojihelper.util.ScreenUtil

@SuppressLint("ViewConstructor")
/**
 * OnmyojiHelper
 * </p>
 * Created by liut on 2017/12/9 0009.
 */
class FloatCtrlView(context: Context?, listener: OnClickListener) : LinearLayout(context) {

    companion object {
        val TAG = "FloatCtrlView"
    }

    private var windowManager: WindowManager
    private var params: WindowManager.LayoutParams

    init {
        LayoutInflater.from(context)?.inflate(R.layout.float_ctrl_view, this)
        windowManager = context?.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        findViewById<Button>(R.id.start_bt).setOnClickListener(listener)
        findViewById<Button>(R.id.stop_bt).setOnClickListener(listener)
        findViewById<Button>(R.id.close_bt).setOnClickListener(listener)
        params = WindowManager.LayoutParams()
        params.type = WindowManager.LayoutParams.TYPE_PHONE // 类型
        params.flags = FLAG_NOT_TOUCH_MODAL or FLAG_NOT_FOCUSABLE or FLAG_LAYOUT_IN_SCREEN
        params.format = PixelFormat.TRANSLUCENT // 不设置这个弹出框的透明遮罩显示为黑色
        params.width = WindowManager.LayoutParams.WRAP_CONTENT
        params.height = WindowManager.LayoutParams.WRAP_CONTENT
        params.gravity = Gravity.END or Gravity.TOP
    }

    fun show() {
        windowManager.addView(this, params)
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if (event == null) return super.onTouchEvent(event)
        LogUtil.d(TAG, "event >> $event.x  $event.y")
        params.x = ScreenUtil.getWidth(context) - event.rawX.toInt() - 50
        params.y = event.rawY.toInt() - 100
        windowManager.updateViewLayout(this, params)
        return super.onTouchEvent(event)
    }

    fun remove() {
        windowManager.removeViewImmediate(this)
    }

}